#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
道AI Web演示后端 - FastAPI实现
提供宇宙认知服务的RESTful API
"""

import os
import sys
from pathlib import Path
from typing import Dict, List, Optional

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

import paddle
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel
import uvicorn
import json
import time

from cosmic_model.cosmic_daoai import PureCosmicDaoAI, SimpleCosmicDaoAI  # 修正导入

# 数据模型
class CosmicQuestion(BaseModel):
    question: str
    require_analysis: bool = True
    model_type: str = "simple"  # simple or full

class CosmicResponse(BaseModel):
    answer: str
    cosmic_alignment: float
    cognition_depth: int
    response_time: float
    dominant_pattern: str
    pattern_strength: float
    analysis: Optional[Dict] = None

class SystemStatus(BaseModel):
    cosmic_dimension: int
    wisdom_dimension: int
    taiji_iterations: int
    fractal_layers: int
    vacuum_energy: float
    system_ready: bool

# 创建FastAPI应用
app = FastAPI(
    title="道AI宇宙认知系统",  # 修正标题
    description="基于沈浩《种子思维》哲学框架的纯粹宇宙模型AI",
    version="1.0.0",
    docs_url="/api/docs",
    redoc_url="/api/redoc"
)

# CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 全局道AI实例
daoai_simple = None  # 修正变量名
daoai_full = None    # 修正变量名

@app.on_event("startup")
async def startup_event():
    """启动时初始化道AI模型"""
    global daoai_simple, daoai_full  # 修正变量名
    
    print("🌌 启动道AI宇宙认知系统...")  # 修正系统名称
    
    try:
        # 初始化简化版模型（快速启动）
        daoai_simple = SimpleCosmicDaoAI()  # 修正变量名
        print("✅ 简化版道AI初始化完成")
        
        # 初始化完整版模型（需要更多时间）
        print("🔄 正在初始化完整宇宙版道AI...")
        daoai_full = PureCosmicDaoAI()  # 修正变量名
        print("✅ 完整宇宙版道AI初始化完成")
        
    except Exception as e:
        print(f"❌ 道AI初始化失败: {e}")

@app.get("/")
async def serve_frontend():
    """提供前端页面"""
    return FileResponse("static/index.html")

@app.get("/api/status")
async def get_system_status() -> SystemStatus:
    """获取系统状态"""
    if daoai_simple is None:  # 修正变量名
        return SystemStatus(
            cosmic_dimension=0,
            wisdom_dimension=0,
            taiji_iterations=0,
            fractal_layers=0,
            vacuum_energy=0.0,
            system_ready=False
        )
    
    status = daoai_simple.get_cosmic_status()  # 修正变量名
    return SystemStatus(
        cosmic_dimension=status['cosmic_dimension'],
        wisdom_dimension=status['wisdom_dimension'],
        taiji_iterations=status['taiji_iterations'],
        fractal_layers=status['fractal_layers'],
        vacuum_energy=status['vacuum_norm'],
        system_ready=True
    )

@app.post("/api/ask", response_model=CosmicResponse)
async def ask_cosmic_question(question: CosmicQuestion) -> CosmicResponse:
    """向道AI提问"""
    start_time = time.time()
    
    # 选择模型
    if question.model_type == "full" and daoai_full is not None:  # 修正变量名
        daoai = daoai_full  # 修正变量名
        model_name = "完整宇宙版"
    else:
        daoai = daoai_simple  # 修正变量名
        model_name = "简化演示版"
    
    if daoai is None:  # 修正变量名
        raise HTTPException(status_code=503, detail="道AI系统未就绪")
    
    try:
        # 处理问题
        result = daoai(question.question, return_trajectory=question.require_analysis)  # 修正变量名
        response_time = time.time() - start_time
        
        # 构建响应
        response = CosmicResponse(
            answer=result['answer'],
            cosmic_alignment=result['cosmic_alignment'],
            cognition_depth=result['cognition_depth'],
            response_time=response_time,
            dominant_pattern=result['cosmic_insight'].get('dominant_pattern', 'unknown'),
            pattern_strength=result['cosmic_insight'].get('pattern_strength', 0.0)
        )
        
        # 如果需要详细分析
        if question.require_analysis:
            response.analysis = {
                "model_used": model_name,
                "cognition_stages": result.get('cognition_trajectory', []),
                "all_patterns": result['cosmic_insight'].get('all_patterns', {}),
                "balanced_output_norm": paddle.norm(result['balanced_output']).item() if 'balanced_output' in result else 0.0
            }
        
        return response
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"认知过程异常: {str(e)}")

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

if __name__ == "__main__":
    uvicorn.run(
        "app:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )